<template>
	<view class="wm container">
		<view class="tips">
			<uni-icons type="star" color="#ff7d5d"></uni-icons>	
			完成个人信息完善可获得100积分
			<uni-icons type="star" color="#ff7d5d"></uni-icons>	
		</view>
		<view class="form">
				<uni-forms ref="form" :modelValue="FormData" :rules="rules">
				<!-- 邀请码 -->
				<uni-forms-item label="邀请码:" name="checkinvitationcode" :label-width="labW" label-align="right" required>
					<uni-easyinput type="text" v-model="FormData.checkinvitationcode" placeholder="请填写邀请码"></uni-easyinput>
				</uni-forms-item>
				<!-- 头像 -->
				<uni-forms-item label="头像:" name="checkinvitationcode" :label-width="labW" label-align="right" required>
					<view class="avatar-box" @click="getAvatar">
						<image class="avatar" :src="avatar ? avatar : '../../static/132.jpg' "></image>
						<text class="text">点击上传</text>
					</view>
				</uni-forms-item>
				<!-- 真实姓名 -->
				<uni-forms-item label="真实姓名:" name="name" :label-width="labW" label-align="right" required>
					<uni-easyinput type="text" v-model="FormData.name" placeholder="请输入真实姓名"></uni-easyinput>
				</uni-forms-item>
				<!-- 昵称 -->
				<uni-forms-item label="昵称:" name="nickname" :label-width="labW" label-align="right" required>
					<uni-easyinput type="text" v-model="FormData.nickname" placeholder="请输入昵称"></uni-easyinput>
				</uni-forms-item>
				<!-- 微信号 -->
				<uni-forms-item label="微信号:" name="wxnumber" :label-width="labW" label-align="right" required>
					<uni-easyinput type="text" v-model="FormData.wxnumber" placeholder="请输入微信号"></uni-easyinput>
				</uni-forms-item>
				<!-- 民族 -->
				<uni-forms-item label="民族:" name="nation" required :label-width="labW" label-align="right">
					<uni-data-select
						v-model="FormData.nation"
						:localdata="nations"
					></uni-data-select>
				</uni-forms-item>
				<!-- 性别 -->
				<uni-forms-item label="性别:" name="sex" required :label-width="labW" label-align="right">
					<view class="sex">
						<uni-data-checkbox v-model="FormData.sex" :localdata="sexs" selected-color="#68d0e3" selected-text-color="#68d0e3"/>
					</view>
				</uni-forms-item>
				<!-- 身份证号码 -->
				<uni-forms-item label="身份证号:" name="idcard" labelWidth="100" required :label-width="labW" label-align="right">
					<uni-easyinput type="text" v-model="FormData.idcard" placeholder="请输入身份证号" />
				</uni-forms-item>
				<!-- 手机号码 -->
				<uni-forms-item label="手机号:" name="phone" labelWidth="100" required ref="phone" :label-width="labW" label-align="right">
					<uni-easyinput type="text" v-model="FormData.phone" placeholder="请输入手机号" />
				</uni-forms-item>
				<!-- 验证码 -->
				<uni-forms-item label="验证码:" name="verification_code" labelWidth="100" required :label-width="labW" label-align="right">
					<view class="form-ib">
						<uni-easyinput type="text" class="input" v-model="FormData.verification_code" placeholder="请输入验证码" />
					    <button :class="isDisabled? 'button0':'button'"  @click="getVerificationCode">{{btnText}}</button>
					</view>
				</uni-forms-item>
				<!-- 毕业学校 -->
				<uni-forms-item label="毕业学校:" name="schoolname" labelWidth="100" required :label-width="labW" label-align="right">
					<uni-easyinput type="text" v-model="FormData.schoolname" placeholder="请填写毕业学校名称"></uni-easyinput>
				</uni-forms-item>
				<!-- 毕业专业 -->
				<uni-forms-item label="毕业专业:" name="major" labelWidth="100" required :label-width="labW" label-align="right">
					<uni-easyinput type="text" v-model="FormData.major" placeholder="请输入毕业专业,或者填写'无'"></uni-easyinput>
				</uni-forms-item>
				<!-- 高考分数 -->
				<uni-forms-item label="高考成绩:" name="score" labelWidth="100" required>
					<uni-easyinput type="text" v-model="FormData.score" placeholder="请输入高考成绩"></uni-easyinput>
				</uni-forms-item>
				<button  @click="save" class="savebtn">保存</button>
			</uni-forms>
			
		</view>
	</view>
</template>

<script>
	import {mapState,mapMutations} from "vuex"
	export default {
		data() {
			return {
				labW:"150rpx",
				FormData:{
					checkinvitationcode:"", //邀请码
					name:"", //真实姓名
					nickname:"", //昵称
					wxnumber:"", //微信号
				    nation:"", //民族
					sex:1, //性别
					idcard:"", //身份证号
					phone:"", //手机号码
					verification_code:"", //验证码
					schoolname:"", //毕业学校名称
					major:"", //毕业专业
					score:"", //高考成绩
				},
				//头像地址
				portImageUrl: getApp().globalData.portImageUrl,
				//民族集合
				nations:[],
				//性别集合
				sexs:[
					{
						text:"男",
						value:1
					},
					{
						text:"女",
						value:0
					}
				],
				//手机验证码
				isDisabled:false,
				btnText:"获取验证码",
				getCodePhone:"",
				portCode:"",
				//表单验证
				rules:{
					
					//邀请码
					checkinvitationcode:{
						rules:[
							{
								required:true,
								errorMessage:"请输入邀请码"
							}
						]
					},
					//真实姓名
					name:{
						rules:[
							{
								required:true,
								errorMessage:"请输入真实姓名"
							}
						]
					},
					//真实姓名
					nickname:{
						rules:[
							{
								required:true,
								errorMessage:"请输入昵称"
							}
						]
					},
					//真实姓名
					wxnumber:{
						rules:[
							{
								required:true,
								errorMessage:"请输入微信号"
							}
						]
					},
					//对idcard进行验证
					idcard:{
						rules:[
							{
								required:true,
								errorMessage:"请输入身份证号"
							},
							{
								validateFunction:(rule,value,data,callback) => {
									var city = {
									    11: "北京",
									    12: "天津",
									    13: "河北",
									    14: "山西",
									    15: "内蒙古",
									    21: "辽宁",
									    22: "吉林",
									    23: "黑龙江 ",
									    31: "上海",
									    32: "江苏",
									    33: "浙江",
									    34: "安徽",
									    35: "福建",
									    36: "江西",
									    37: "山东",
									    41: "河南",
									    42: "湖北 ",
									    43: "湖南",
									    44: "广东",
									    45: "广西",
									    46: "海南",
									    50: "重庆",
									    51: "四川",
									    52: "贵州",
									    53: "云南",
									    54: "西藏 ",
									    61: "陕西",
									    62: "甘肃",
									    63: "青海",
									    64: "宁夏",
									    65: "新疆",
									    71: "台湾",
									    81: "香港",
									    82: "澳门",
									    91: "国外 "
									};
									var code_regular = /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[12])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)?$/i;
									var tip = '';
									var pass = true;
									if (!code_regular.test(value) || (value.length != 18 && value.length != 15)) {
									    tip = '请输入有效身份证号码';
									    pass = false;
									} else if (!city[value.substr(0, 2)]) {
									    // tip = "地址编码错误";
										tip="请输入有效身份证号码"
									    pass = false;
									} else {
									    if (value.length == 18) {
									        value = value.split('');
									        // ∑(ai×Wi)(mod 11)
									        // 加权因子
									        var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]; // wi
									        // 校验位
									        var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2]; // mod(sum, 11)
									        var sum = 0;
									        var ai = 0;
									        var wi = 0;
									        for (var i = 0; i < 17; i++) {
									            ai = value[i];
									            wi = factor[i];
									            sum += ai * wi;
									        }
									        if (parity[sum % 11] != value[17]) {
									            // tip = '校验位错误';
												tip="请输入有效身份证号码"
									            pass = false;
									        }
									    }
									}
									if (!pass) {
									    callback(tip);
									}
									return pass;
								}
							}
						]
					},
					//手机号码
					phone:{
						rules:[
							{
								required:true,
								errorMessage:"请输入手机号"
							},
							{
								validateFunction:(rule,value,data,callback) => {
									let RegExp = /^(?:(?:\+|00)86)?1(?:(?:3\d)|(?:4[5-9])|(?:5[0-35-9])|(?:6[2567])|(?:7[0-8])|(?:8\d)|(?:9[189]))\d{8}$/
									if(!RegExp.test(this.phone)){
										callback("请输入有效手机号")
									}
									callback()
								}
							}
						]
					},
					//验证码
					verification_code:{
						rules:[
							{
								required:true,
								errorMessage:"请输入验证码"
							}
						]
					},
					//验证毕业学校名称
					schoolname:{
						rules:[
							{
								required:true,
								errorMessage:"请填写毕业学校名称"
							}
						]
					},
					//验证毕业专业
					major:{
						rules:[
							{
								required:true,
								errorMessage:"请输入毕业专业，或者填写'无'"
							}
						]
					},
					//验证高考成绩
					score:{
						rules:[
							{
								required:true,
								errorMessage:"请输入高考成绩"
							},
							{
								validateFunction:(rule,value,data,callback)=>{
									let RegExp = /^\d{0,3}(\.\d)?$/
									if(RegExp.test(value) && (value <= 750 &&  value > 0) ){
										callback()
									}else{
										callback("请输入正确的高考分数")
									}
								}
							}
						]
					},
					
				}
			}
		},
		computed:{
			...mapState("m_user",["userInfo","id"]),
			//头像
			avatar(){
				if(this.userInfo.avatarurl.length <= 0){
					return "";
				}else{
					if(this.userInfo.avatarurl.indexOf("/") == -1){
						return this.portImageUrl +"/avatar/"+ this.userInfo.avatarurl
					}else{
						return this.userInfo.avatarurl
					}
				}
				
			}
		},
		onReady(){
		    this.$refs.form.setRules(this.rules);
		},
		onShow(){
			this.init_data()
		},
		methods: {
			...mapMutations("m_user",['updateUserInfo',"updateToken"]),
	
			/**
			 * 初始化数据
			 */
			async init_data(){
				//初始化昵称
				this.FormData.nickname = this.userInfo.nickname
				//初始化民族
				//查询数据库中的民族，把获取回来的数据保存到当前的nations数组中
				const {data:res} = await uni.$http.post("Users/nation")
				if(res.meta.status == 0) return uni.$showMsg("查询民族失败")
				let nation = []
				for( let index in res.data){
					nation[index] = {
						"text":res.data[index]['name'],
						"value":res.data[index]['name']
					}
				}
				this.nations = nation
				//初始化民族
				this.FormData.nation = this.userInfo.nation
			},
			/**
			 * 保存
			 */
			save(){
				uni.showLoading()
				this.$refs.form.validate().then(async (res) => {
					if(res.phone != this.getCodePhone) return uni.$showMsg("请输入获取验证码的手机号");
					if(res.verification_code != this.portCode) return uni.$showMsg("验证码错误");
					//组织要修改的数据
					let $query = {
						"token":this.userInfo.token,
						"id":this.userInfo.id,
						"name":res.name,
						"checkinvitationcode": res.checkinvitationcode,
						"idcard": res.idcard,
						"major": res.major,
						"name": res.name,
						"nation": res.nation,
						"nickname": res.nickname,
						"phone": res.phone,
						"schoolname": res.schoolname,
						"score": res.score,
						"sex": res.sex,
						"wxnumber": res.wxnumber
					}
					//请求数据接口修改数据
					const {data:result} = await uni.$http.post("Users/updateUserInfo",$query)
					if(result.meta.status == 0) return uni.$showMsg(result.meta.msg);
					result.data['token'] = this.userInfo.token
					//修改成功之后更新storage中的用户信息
					this.updateUserInfo(result.data);
					this.updateToken(this.userInfo.token);
					uni.hideLoading()
					uni.$showMsg(result.meta.msg);
					//返回管理页面
					setTimeout(()=>{
						uni.navigateBack({
							url:"/page/my/my"
						})
					},1500);
				}).catch(err => {
					uni.hideLoading()
					uni.$showMsg(err[0].errorMessage);
				})
			},
			/**
			 * 获取验证码
			 */
			async getVerificationCode(){
				//如果按钮处于禁用状态不可以点击
				if(this.isDisabled){return}
				let phone = this.FormData.phone
				if(phone.length == 0){
					return uni.$showMsg("请输入手机号");
				}else{
					let RegExp = /^(?:(?:\+|00)86)?1(?:(?:3\d)|(?:4[5-9])|(?:5[0-35-9])|(?:6[2567])|(?:7[0-8])|(?:8\d)|(?:9[189]))\d{8}$/
					if(!RegExp.test(this.FormData.phone)){
					  return uni.$showMsg("请输入有效手机号");
					}
					//开始计时器
				    this.startCountdown();
					//把获取验证码的手机号保存起来
					this.getCodePhone = this.FormData.phone;
					//创建请求参数
					let require = {
						"tel":this.FormData.phone,
						"codetype":5
					}
					//向后台请求发送手机验证码的接口
					const {data:result} = await uni.$http.post("Users/sendMes",require);
					if(result.meta.status == 0) return uni.$showMsg(result.meta.msg);
					this.portCode = result.data.code
					uni.$showMsg("验证码已发送");
				}
			},
			startCountdown(){
				let count = 60; //倒计时的秒数
				const timer = setInterval(() => {
					if (count <= 0) {
					  clearInterval(timer); // 倒计时结束，清除计时器
					  this.resetButtonState(); // 复原按钮状态
					} else {
					  this.btnText = `${count}s后再获取`; // 更新按钮文本内容
					  this.isDisabled = true; // 禁用按钮
					  count--; // 减少剩余时间
					}
				}, 1000);
				
			},
			resetButtonState() {
			  this.btnText = '获取验证码'; // 恢复按钮文本内容
			  this.isDisabled = false; // 启用按钮
			},
			/**
			 * 跳转到上传头像
			 */
			getAvatar(){
				uni.navigateTo({
					url:"/subpkg/image_crop/image_crop"
				})
			}
			//--
		}
		
	}
</script>

<style lang="scss">
.container{
	padding-bottom:50rpx;
}
.tips{
	text-align:center;
	font-size:25rpx;
	color:#ff7d5d;
	padding:25rpx;
	padding-bottom:0rpx;
}
.form{
	background-color:#fff;
	margin:30rpx 0 50rpx 0;
	padding:20rpx;
	border-radius: 15rpx;
}
.savebtn{
	background:linear-gradient(to  right,#feb27a,#ff7d5d);
	color:#fff;
	height: 35px;
	border:0;
	line-height: 35px;
	&:active{
		background:linear-gradient(to  right,#eba470,#e97055);
	}
}
.sex{
	height: 35px;
	line-height: 35px;
	display: flex;
	align-items: center;
}
/*手机号验证码*/
.form-ib{
	display: flex;
	justify-content: space-around;
	align-items: center;
}
.input{
	width: 40%;
}
.button{
	margin-left:10rpx;
	background:linear-gradient(to right,#93bdf3,#68d0e3);
	width:108px;
	height: 35px;
	line-height: 35px;
	color:#fff;
	border: 0;
	font-size:30rpx;
}
.button0{
	margin-left:10rpx;
	background:#ccc;
	width:108px;
	height: 35px;
	line-height: 35px;
	color:#fff;
	border: 0;
	font-size:30rpx;
}
/*手机号码验证结束*/
/*头像样式开始*/
.avatar-box{
	display: flex;
	justify-content: left;
	align-items: center;
	.text{
		color: #999;
		margin-left:10rpx;
	}
}
.avatar{
	width:70rpx;
	height:70rpx;
	border-radius: 35rpx;
}
/*头像样式结束*/
</style>
